package com.faithbj.danaliverpool.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.faithbj.danaliverpool.service.TemplateService;

/**
 * @author jrn E-mail: rinanjin@gmail.com
 * @version 0.1 
 * 创建时间：2012-7-6 下午11:46:22
 * 类说明
 */
@Service("templateService")
public class TemplateServiceImpl implements TemplateService
{
	private static Logger logger = LoggerFactory.getLogger(TemplateServiceImpl.class);
	
	@Value("${templatePath}")
	private String templatePath;

	@Override
	public List<File> list()
	{
		File file = new File(templatePath);
		if(!file.exists())
		{
			file.mkdirs();
		}
		File[] files = file.listFiles();
		if(files != null)
		{
			return Arrays.asList(files);
		}
		
		return null;
	}

	@Override
	public String content(String fileName)
	{
		File file = new File(templatePath + File.separator + fileName);
		if(file.exists())
		{
			try
			{
				BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(templatePath + File.separator + fileName)));
				String line = reader.readLine();
				StringBuffer buffer = new StringBuffer();
				while(line != null)
				{
					buffer.append(line);
					line = reader.readLine();
				}
				reader.close();
				return buffer.toString();
			}
			catch (FileNotFoundException e)
			{
				logger.error(e.getMessage());
			}
			catch (IOException e)
			{
				logger.error(e.getMessage());
			}
		}
		return null;
	}

	@Override
	public void save(String fileName, String content)
	{
		try
		{
			FileOutputStream fos = new FileOutputStream(templatePath + File.separator + fileName);
			fos.write(content.getBytes());
			fos.flush();
			fos.close();
		} 
		catch (FileNotFoundException e)
		{
			logger.error(e.getMessage());
		}
		catch (IOException e)
		{
			logger.error(e.getMessage());
		}

	}

	@Override
	public void create(String fileName)
	{
		File file = new File(templatePath + File.separator + fileName);
		
		if(!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{
				logger.error(e.getMessage());
			}
		}

	}

	@Override
	public void delete(String fileName)
	{
		File file = new File(templatePath + File.separator + fileName);
		file.delete();
	}

}
